package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliLsOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;

    private Log logger = Log.get();



    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate  = 5000)
    public void checkOrder() throws Exception {
//        logger.info("乐刷订单查询..");
        Calendar c = Calendar.getInstance();

        TOrderInfo query = new TOrderInfo();
        query.setChannelType("alipay");
        query.setChannel("alipay_ls_h5");
        query.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(query);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for(TOrderInfo orderInfo:orderInfos){
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
           TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://syt.leshuazf.com/merchant/transaction/v2/listTransaction";
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String merchantId = cookieObj.getString("merchantId");
            String sessionId =  cookieObj.getString("uatk");
            String username =  cookieObj.getString("username");

            JSONObject queryObj = new JSONObject();
            queryObj.put("merchantId",merchantId);
            JSONArray targetMerchantIdList = new JSONArray();
            targetMerchantIdList.add(merchantId);
            queryObj.put("targetMerchantIdList",targetMerchantIdList);
            queryObj.put("pageNo",1);
            queryObj.put("tradeType",1);
            queryObj.put("targetMerchantId",merchantId);
            queryObj.put("payType",0);
            queryObj.put("sessionId",sessionId);
            queryObj.put("startTime",startTimeStr);
            queryObj.put("pageSize",20);
            queryObj.put("version",107003);
            queryObj.put("endTime",endTimeStr);
            queryObj.put("loginUserName",username);

            HashMap<String, String> headerMap = new HashMap();
//            headerMap.put("Authorization","Bearer "+userRecipientInfo.getCookie());
//            logger.info("乐刷订单查询请求："+queryObj.toJSONString());
            String httpResponse = HttpUtils.sendJsonMessage(url,headerMap,queryObj.toJSONString());
            JSONObject resultObj = JSONObject.parseObject(httpResponse);
            int resultCode = resultObj.getInteger("error_code");
            if(resultCode==0){
                JSONArray recordList = resultObj.getJSONArray("data");
                for (int i=0;i<recordList.size();i++){
                    JSONObject recordObj = recordList.getJSONObject(i);
                    if(recordObj.getString("payType").equals("1") && recordObj.getString("status").equals("1") && orderInfo.getMoney().equals(recordObj.getLong("amount"))){
                        if(recordObj.getString("orderId").equals(orderInfo.getPay3rdOrderNo())){//成功订单
                            logger.info("乐刷订单查询.."+recordObj);
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(recordObj.getString("orderId"));
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(recordObj.getString("payTime"));

                            msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                            chargeService.updateOrderPayResult(false,orderInfo.getId(),msgPayResult,false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("乐刷订单回调..订单号："+orderInfo.getId()+" 金额："+orderInfo.getMoney());
                        }
                    }
                }
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
